package com.marketingcenter.service.impl;

import com.marketingcenter.entity.PackageCard;
import com.marketingcenter.repository.PackageCardRepository;
import com.marketingcenter.service.PackageCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 套餐卡服务实现类
 */
@Service
public class PackageCardServiceImpl extends PromotionServiceImpl<PackageCard> implements PackageCardService {

    @Autowired
    private PackageCardRepository packageCardRepository;

    @Override
    protected JpaRepository<PackageCard, Long> getRepository() {
        return packageCardRepository;
    }

    @Override
    public List<PackageCard> findByStatus(Integer status) {
        return packageCardRepository.findByStatus(status);
    }

    @Override
    public List<PackageCard> findActivePromotions() {
        LocalDateTime now = LocalDateTime.now();
        return packageCardRepository.findByStartTimeLessThanEqualAndEndTimeGreaterThanEqual(now, now);
    }

    @Override
    public boolean purchasePackageCard(Long cardId, Long userId) {
        // 实际实现中需要记录用户购买套餐卡的信息
        // 这里仅做简单示例
        PackageCard card = findById(cardId);
        if (card != null && card.getStatus() == 1) { // 1表示进行中
            // 检查库存
            if (card.getSoldQuantity() >= card.getTotalQuantity()) {
                return false;
            }
            // 增加已售出数量
            card.setSoldQuantity(card.getSoldQuantity() + 1);
            update(card);
            return true;
        }
        return false;
    }

    @Override
    public double getDiscountRate(Long cardId) {
        // 计算折扣力度 = (原价 - 套餐价) / 原价
        PackageCard card = findById(cardId);
        if (card == null) {
            return 0;
        }
        double originalPrice = card.getOriginalPrice().doubleValue();
        double packagePrice = card.getPackagePrice().doubleValue();
        if (originalPrice <= 0) {
            return 0;
        }
        return (originalPrice - packagePrice) / originalPrice;
    }

}